#include <ESP8266WiFi.h>       // 本程序使用 ESP8266WiFi库
#include <ESP8266WiFiMulti.h>  //  ESP8266WiFiMulti库
#include <ESP8266WebServer.h>  //  ESP8266WebServer库
ESP8266WiFiMulti wifiMulti;  // 建立ESP8266WiFiMulti对象,对象名称是'wifiMulti'
IPAddress local_IP(192, 168, 1, 12); // 你想要的静态IP
IPAddress local_IP_AP(192, 168, 1,1); // 你想要的静态IP
IPAddress gateway(192, 168, 1, 1);     // 网关地址
IPAddress subnet(255, 255, 255, 0);    // 子网掩码
ESP8266WebServer esp8266_server(80);  // 建立ESP8266WebServer对象，对象名称为esp8266_server

                                      // 括号中的数字是网路服务器响应http请求的端口号
                                      // 网络服务器标准http端口号为80，因此这里使用80为端口号
//  生成网页响应报文格式
//  参数buttonText为按钮显示的文字，默认为"开灯"
String makeResponse(const String &buttonText = "开灯", int refreshTime = 3600) {
  String htmlCode;
  htmlCode += "<!DOCTYPE html> <html>\n";
  htmlCode += "<head>\n";
  htmlCode += "<meta charset=\"UTF-8\">\n";
  htmlCode += "<title>艾莉点灯</title>\n";
  htmlCode += "<style>\n";
  htmlCode += "body {\n";
  htmlCode += "  font-family: Arial, sans-serif;\n";
  htmlCode += "  text-align: center;\n";
  htmlCode += "  margin-top: 50px;\n";
  htmlCode += "  background-image: url('http://hbimg.huaban.com/2de61f00bca7f42f1c33717b4b7d3cada02703af14241a-5mRAbP');\n";
  htmlCode += "  background-size: cover;\n";        // 调整为 contain，确保图片完整显示
  htmlCode += "  background-attachment: fixed;\n";  // 背景图片固定不动
  htmlCode += "  background-repeat: no-repeat;\n";
  htmlCode += "  background-position: center center;\n";  // 明确水平和垂直方向都居中
  htmlCode += "}\n";
  htmlCode += "h1 {\n";
  htmlCode += "  color: #FFB6C1;\n";
  htmlCode += "  font-size: 24px;\n";
  htmlCode += "  padding: 10px 20px;\n";
  htmlCode += "  margin-top: 20px;\n";
  htmlCode += "}\n";
  htmlCode += "</style>\n";
  htmlCode += "</head>\n";
  htmlCode += "<body><h1>艾莉点灯</h1>\n";
  htmlCode += "<form action=\"/LED\" method=\"POST\">\n";
  htmlCode += "<button type=\"submit\">";
  htmlCode += buttonText;
  htmlCode += "</button>\n";
  htmlCode += "</form>\n";
  htmlCode += "<script>\n";
  htmlCode += "setTimeout(function() { window.location.reload(); }, " + String(refreshTime * 1000) + ");\n";
  htmlCode += "</script>\n";
  htmlCode += "</body>\n";
  htmlCode += "</html>\n";
  return htmlCode;
}

void setup_server(void)
{
  Serial.println('\n');           
  Serial.print("Connected to ");   
  Serial.println(WiFi.SSID());    
  Serial.print("IP address:\t");  
  Serial.println(WiFi.localIP()); 
  //--------"启动网络服务功能"程序部分开始--------
  esp8266_server.begin();
  esp8266_server.on("/", handleRoot);
  esp8266_server.on("/LED", HTTP_POST, handleLED);  // 设置处理LED控制请求的函数'handleLED'
  esp8266_server.onNotFound(handleNotFound);
  //--------"启动网络服务功能"程序部分结束--------
  Serial.println("HTTP esp8266_server started");
}

void blinkLED(int pin, int times) {
  pinMode(pin, OUTPUT);
  for (int i = 0; i < times; i++) {
    digitalWrite(pin, LOW);
    delay(100);
    digitalWrite(pin, HIGH);
    delay(100);
  }
}

void setup(void) {
  Serial.begin(9600);  // 启动串口通讯
  pinMode(0, OUTPUT);
  pinMode(2, OUTPUT);
  digitalWrite(0, HIGH);
  digitalWrite(2, HIGH);
  // 通过addAp函数存储  WiFi名称     WiFi密码
//  wifiMulti.addAP("YG", "xiaokeai");
  wifiMulti.addAP("feibot03", "feibot.com");
  // wifiMulti.addAP("ESP", "1111aaaa");
  WiFi.config(local_IP, gateway, subnet);
  // 连接到指定的WiFi网络,超时最多重试3次
  int i = 1;
  int timeout = 3;
  while (i <= timeout) {
    if (wifiMulti.run() == WL_CONNECTED) {
      setup_server();
      break;
    }
    delay(50);
        Serial.print("connecting...");  
        Serial.print(i++);
         Serial.println();
  }
  if (i > timeout)
  {
    Serial.println("WiFi connect timeout");
    
    blinkLED(2, 5); // 闪烁LED

    // 设置ESP8266为AP模式
    WiFi.mode(WIFI_AP);
    WiFi.softAPConfig(local_IP_AP, gateway, subnet);
    WiFi.softAP("ESP8266-AP");
    // 设置静态IP在192.168.1.1

    // 启动服务器并处理AP配置页面
    8266_server.on("/", HTTP_GET, handleAPConfig);
    8266_server.on("/updateAP", HTTP_POST, handleUpdateAP);
    8266_server.begin();
    Serial.println("AP mode started");
  }


}

void loop(void) {
  esp8266_server.handleClient();  // 处理http服务器访问
}
void handleRoot() {
  bool led_state = digitalRead(2);
  // String backgroundUrl = led_state ? "http://i0.hdslb.com/bfs/article/f90483bb326b517f8a6dd0a23dcbe51c1efa2905.jpg" : "http://hbimg.huaban.com/2de61f00bfsarticle/2de61f00bca7f42f1c33717b4b7d3cada02703af14241a-5mRAbP";
  String buttonText = led_state ? "开灯" : "关灯";
  esp8266_server.send(200, "text/html; charset=UTF-8", makeResponse(buttonText));
  Serial.println("New Web access");
}

//处理LED控制请求的函数'handleLED'
void handleLED() {
  Serial.println("LED SET");
  digitalWrite(0, !digitalRead(0));            // 改变LED的点亮或者熄灭状态
  digitalWrite(2, !digitalRead(2));            // 改变LED的点亮或者熄灭状态
  esp8266_server.sendHeader("Location", "/");  // 跳转回页面根目录
  esp8266_server.send(303);                    // 发送Http相应代码303 跳转
}
// 设置处理404情况的函数'handleNotFound'
void handleNotFound() {                                      // 当浏览器请求的网络资源无法在服务器找到时，
  esp8266_server.send(404, "text/plain", "404: Not found");  // NodeMCU将调用此函数。
}


// 处理AP模式下的网页请求
void handleAPConfig() {
  String htmlCode = APConfigPage(); // 假设这是生成AP配置页面的函数
  8266_server.send(200, "text/html; charset=UTF-8", htmlCode);
}

// 生成AP配置页面
String APConfigPage() {
  String htmlCode;
  htmlCode += "<!DOCTYPE html> <html><head><title>AP Configuration</title></head><body>";
  htmlCode += "<h1>AP Configuration</h1>";
  htmlCode += "<form method='POST' action='/updateAP'>";
  htmlCode += "<label for='ssid'>SSID:</label><br>";
  htmlCode += "<input type='text' id='ssid' name='ssid' required><br>";
  htmlCode += "<label for='password'>Password:</label><br>";
  htmlCode += "<input type='password' id='password' name='password' required><br>";
  htmlCode += "<label for='ip'>IP Address:</label><br>";
  htmlCode += "<input type='text' id='ip' name='ip' placeholder='192.168.1.x' required><br>";
  htmlCode += "<input type='submit' value='Submit'>";
  htmlCode += "</form></body></html>";
  return htmlCode;
}

// 处理AP配置更新
void handleUpdateAP() {
  String ssid = 8266_server.arg("ssid");
  String password = 8266_server.arg("password");
  String ip = 8266_server.arg("ip");
  
  // 更新静态IP
  local_IP.fromString(ip);
    8266_server.close();
    WiFi.mode(WIFI_STA);
    Serial.println("AP mode stopped");
    Serial.println(ssid.c_str());
    Serial.println(password.c_str());
    Serial.println(ip.c_str());
  WiFi.begin(ssid.c_str(), password.c_str());
  // 添加新的WiFi网络
  int i = 1;
  int timeout = 3;
  while (i <= timeout) 
  {
if (WiFi.status() == WL_CONNECTED) {
  blinkLED(2, 5); // 闪烁LED
    WiFi.config(local_IP, gateway, subnet);
    setup_server();
}
delay(50);
Serial.print("connecting...");  
Serial.print(i++);
Serial.println();
  }
  if (i > timeout) {
    Serial.println("WiFi connect timeout");
    digitalWrite(2, LOW); // 常亮LED
  }
}